package cn.jdy.plugins.wap;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mongodb.util.JSON;

import cn.jdy.authority.entity.User;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.HttpUtil;
import cn.jdy.framework.util.JsonUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.NewsXysgajM;
import cn.jdy.plugins.entity.Productx;
import cn.jdy.plugins.entity.xysgajM.Reports;
import cn.jdy.plugins.service.xysgajM.NewsXysgajMService;
import cn.jdy.plugins.service.xysgajM.ReportsService;

/**
 * daihu
 * @title 举报控制类
 */
@Controller
@RequestMapping("/reports")
public class ReportsCtrl extends BaseCtrl {
  @Autowired
  private ReportsService reportsService;
  @Autowired
  private ConfService confService;

	//默认列表路径
	private static String viewName = "redirect:/reports/Succes.jsp";
	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		ModelAndView mv = new ModelAndView("/reports.jsp");
		return mv;
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id,String code) {
		ModelAndView mv = new ModelAndView("/reports.jsp"); 
		mv.addObject("data", id==null||id==0 ? id : this.reportsService.find(id));
		mv.addObject("userdata",  toCode(code));
	
		return mv;
	}
	
	
	 /**
   * 授权
   * @param 
   * @return
   */
  @RequestMapping("/toEdit/{id}")
  public String toEdit(@PathVariable Long id) {

    String url=request.getRequestURL().toString().split("toEdit")[0]+"edit/"+id;
    String cdurl=URLEncoder.encode(url);
    //String url = HttpUtil.getURL(WeChatConstant.SERVICE_OPEN, WeChatConstant.ACTION_OAUTH2_CONNECT, appId, URLEncoder.encode(oAuthII_url, "UTF-8"), WeChatConstant.OAUTH2_SOCP_BASE, appId);
    return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx003d8b600a48f618&redirect_uri="+cdurl+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect" ;
  }
  
  /**
   * 获取微信接口里面的用户信息
   * @param 
   * @return
   */
 
  public Map<String, Object> toCode(String code) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    HashMap<String, Object> user=null;
    try {
      //根据code 得到 openid
      String  vre = HttpUtil.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx003d8b600a48f618&secret=1c626ad51858f82ff8eb1307b0b56b73&code="+code+"&grant_type=authorization_code","UTF-8");
      HashMap<String, Object> map=(HashMap<String, Object>) JsonUtil.toObj(vre, Map.class);
      String openId =null;
      if(map.containsKey ("openid")){
          openId =map.get("openid").toString();
      }

      System.out.println(openId+">>>>>.>>>>>openId ");
      //得到 token 唯一凭证
      String  token = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx003d8b600a48f618&secret=1c626ad51858f82ff8eb1307b0b56b73","UTF-8");
      HashMap<String, Object> map2=(HashMap<String, Object>) JsonUtil.toObj(token, Map.class);

      String access_token =null;
      if(map.containsKey ("access_token")){
        access_token =map2.get("access_token").toString();
      }
      System.out.println(access_token+">>>>>.>>>>>access_token ");
      
      if(StringUtil.isNotEmpty(openId)&&StringUtil.isNotEmpty(access_token)){
      //根据openid  token 得到 用户信息
        String  oep = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openId+"&lang=zh_CN","UTF-8");
       // String  oep = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token=q-JQ2alCvTZIIMonM0knWbxVhZKC2bs9uPHyfB8cImNxVHAHAIAvfLMRPO09lKGp1Q5xT5C1ujWyt8WCIx8alnxXSnWZVUg0shmG1bVn9s-rkQtV22oxZURyompRl8avSIWiAIADTH&openid=o1hlOt_gRDWID7pkhyuYVRn7-QPA&lang=zh_CN","UTF-8");
          user=(HashMap<String, Object>) JsonUtil.toObj(oep, Map.class);
     
          System.out.println(oep+">>>>>.>>>>>user ");
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

   return user;
  }
	/**
	 * 保存（更新）新闻
	 * @param Reports
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(Reports Reports, Long pid) {
		ModelAndView mv = new ModelAndView("/Succes.jsp");
		//
		try {
		
			if(Reports.getId()==null) {// 新增文章
				//
//				User user = getUser();
//				Reports.setUserid(user.getId());
//				Reports.setUsername(user.getUsername());
				Reports.setAudit1Status("0");
				Reports.setAudit2Status("0");
				Reports.setReportsTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));//加入举报时间
				//市局需要手动更改时间，如果为空则取正确时间
				if(Reports.getFalseCreateTime() == null || Reports.getFalseCreateTime() == ""){
					Reports.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
//				Reports.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.reportsService.save(Reports);
			//	mv.setViewName(this.viewName.concat("1"));
			} else {//更新文章
				User user = getUser();
				Reports.setUserid(user.getId());
				Reports.setUsername(user.getUsername());
				Reports.setReportsTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));//加入举报时间
				if(Reports.getFalseCreateTime() == null || Reports.getFalseCreateTime() == ""){
					Reports.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}//市局
				this.reportsService.update(Reports);
			//	mv.setViewName(this.viewName.concat("2"));
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, Reports.getId());
			}
			// 清理栏目列表缓存
		
		} catch(Exception e) {
		//	mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "新闻保存异常！", e);
		}

		return mv;
	}
}
